import { createSlice, PayloadAction, createAsyncThunk } from '@reduxjs/toolkit';
import type { RootState } from '../store';
import { loginByUsername } from '@api/login';

interface initialState {
    userInfo: object;
}

const initialState = {
    userInfo: {},
} as initialState;

interface formData {
    username: string;
    password: string;
    remember: boolean;
}

export const loginApi = createAsyncThunk<any, formData>('app/loginApi', async (data: formData) => {
    try {
        let { username, password, remember } = data;
        const response = await loginByUsername(username, password, remember);
        return response;
    } catch (err) {
        let error: any = err; // cast the error for access
        if (!error.response) {
            throw err;
        }
        // We got validation errors, let's return those so we can reference in our component and set form errors
        return '';
    }
});

export const reducerSlice = createSlice({
    name: 'app', // nameSpace
    initialState,
    reducers: {
        setUserInfo: (state, action: PayloadAction<object>) => {
            state.userInfo = action.payload;
        },
    },
    extraReducers: (builder) => {
        // builder.addCase(loginApi.pending, (state, { payload }) => {
        //     console.log('login.pending', payload);
        // });
        builder.addCase(loginApi.fulfilled, (state, action) => {
            console.log('login.fulfilled', action);
        });
        // builder.addCase(loginApi.rejected, (state, { payload }) => {
        //     console.log('login.rejected', payload);
        // });
    },
});

export const { setUserInfo } = reducerSlice.actions;

// Other code such as selectors can use the imported `RootState` type
export const getUserInfo = (state: RootState) => state.app.userInfo;

export default reducerSlice.reducer;
